package com.xcity.game.buycount;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xcity.db.entity.Player;
import com.xcity.game.common.MessageConst;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.request.BuyCountInfoRequest;
import com.xcity.pomelo.request.BuyCountRequest;
import com.xcity.pomelo.response.BuyCountInfoResponse;
import com.xcity.pomelo.response.BuyCountResponse;
import com.xcity.pomelo.response.HintResponse;

import naga.x.App;
import naga.x.game.template.TemplateService;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.Service;
import naga.x.service.ServiceException;

@OPHandler
public class BuyCountService implements Service{

	protected static final Logger LOG = LoggerFactory.getLogger(BuyCountService.class);
	
	@Override
	public void startup() throws ServiceException {
		List<BuyCountTemplate> list = App.getApp().getServiceManager().get(TemplateService.class).getTemplatesList(BuyCountTemplate.class);
		BuyCount.init(list);
	}

	@Override
	public void shutdown() throws ServiceException {
	}
	
	@Override
	public String getId() {
		return getClass().getName();
	}
	
	@PomeloOP(PomeloRoute.BUY_COUNT_INFO)
	protected void requestBuyMoneyInfo(Session session, BuyCountInfoRequest req){
		Player player = session.getClient();
		int type = req.getType();
		BuyCount item = BuyCount.forCode(type);
		if (item == null) {
			player.send(new HintResponse(req.getSerial(), MessageConst.BUY_COUNT_TYPE_ERROR));
			return;
		}
		int leftBuyCount = item.getLeftBuyCount(player);
		int maxCount = item.getMaxCount(player);
		int costStone = item.getCostStone(player);
		int buyValue = item.getBuyValuePerTime();
		player.send(new BuyCountInfoResponse(req.getSerial(), type, leftBuyCount, maxCount, costStone, buyValue));
	}
	
	@PomeloOP(PomeloRoute.BUY_COUNT)
	protected void requestBuyCount(Session session, BuyCountRequest req){
		Player player = session.getClient();
		int type = req.getType();
		BuyCount item = BuyCount.forCode(type);
		if (item == null) {
			player.send(new HintResponse(req.getSerial(), MessageConst.BUY_COUNT_TYPE_ERROR));
			return;
		}
		if (item.getLeftBuyCount(player) <= 0) {
			player.send(new HintResponse(req.getSerial(), MessageConst.SHOP_BUY_NUM_TODAY_MAXED));
			return;
		}
		int cost = item.getCostStone(player);
		if (!player.costStone(cost, item.cause)) {
			player.send(new HintResponse(req.getSerial(), MessageConst.STONE_NOT_ENOUTH));
			return;
		}
		item.addValue(player);
		player.send(new BuyCountResponse(req.getSerial(), type, item.getLeftBuyCount(player), item.getCostStone(player)));
		LOG.info("[BUYCOUNT]ID[{}]TYPE[{}]COST[{}]COUNT[{}]", player.getId(), type, cost, item.getBoughtCount(player));
	}
}
